import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'
import Login from '@/pages/login/login'
import Website from '@/pages/website/index'
import {getToken} from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'
import menuApi from '@/api/system/menu'
import {filterAsyncRouter} from '@/store/modules/permission'

Vue.use(VueRouter)
// 在路由跳转的时候同一个路由多次添加是不被允许的
// 在VUE项目中点击两次路由切换问题
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (to) {
  return VueRouterPush.call(this, to).catch(err => err)
}
// 所有权限通用路由表
// 如首页和登录页和一些不用权限的公用页面
export const constantRouterMap = [
  {
    path: '/',
    name: 'login',
    component: Login
  },
  {
    path: '/website',
    name: 'website',
    component: Website
  }
]

// 创建路由对象
const createRouter = () => new VueRouter({
  mode: 'history',
  base: (process.env.SERVLET_PATH === '' || process.env.SERVLET_PATH === '/') ? '/' : ('/' + process.env.SERVLET_PATH + '/'),
  routes: constantRouterMap
})

const router = createRouter()

// 全局前置守卫
router.beforeEach(async function (to, from, next) {
  // 设置网页的title
  document.title = getPageTitle(to.meta.title)

  // 获取token值
  const token = getToken()
  if (to.path === '/') {
    next()
  }
  // 判断是否包含token
  if (token) {
    // 判断角色是否存在
    if (store.getters.user_roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
      // 根据角色获取路由
      store.dispatch('GetInfo').then(res => { // 拉取user_info
        // 动态路由，拉取菜单
        loadMenus(next, to)
      }).catch((err) => {
        console.log(err)
      })
    } else {
      // 获取动态路由的列表是否为空
      const hasRoutes = await store.getters.permission_routes && store.getters.permission_routes.length > 0
      // 判断是否存在路由
      if (hasRoutes) {
        next()
      } else {
        // 动态路由，拉取菜单
        loadMenus(next, to)
      }
    }
  } else {
    // 跳到登陆页
    next(`/?redirect=${to.path}`)
  }
})

export const loadMenus = (next, to) => {
  menuApi.getPermission().then(res => {
    if (res.status === 200) {
      const accessedRoutes = filterAsyncRouter(res.data, 'admin') || []
      console.log(accessedRoutes)
      // 调取路由菜单
      store.dispatch('generateRoutes', accessedRoutes).then(() => {
        // 添加到路由中
        router.addRoutes(accessedRoutes)
        next({ ...to, replace: true })
      })
    }
  })
}

// 输出路由
export default router
